<template>
    <el-tag
        v-for="tag in dynamicTags"
        :key="tag"
        class="mx-1"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)"
    >
        {{ tag }}
    </el-tag>
    <el-input
        v-if="inputVisible"
        ref="InputRef"
        v-model="inputValue"
        class="ml-1 w-20"
        size="small"
        :maxlength="maxlength || 10"
        @keyup.enter="handleInputConfirm"
        @blur="handleInputConfirm"
    />
    <el-button v-if="showAdd" class="button-new-tag ml-1" size="small" @click="showInput">
        + 新标签</el-button
    >
</template>

<script lang="ts" setup>
import { nextTick, ref, toRefs, computed, watch, reactive } from 'vue';
import { ElInput } from 'element-plus';
const props = defineProps(['labels', 'limit', 'maxlength']);
const emit = defineEmits(['update:labels']);
const { labels } = toRefs(props);

const inputValue = ref('');
const inputVisible = ref(false);
const InputRef = ref();

const tagState = reactive({
    dynamicTags: labels?.value ? [...labels.value] : []
});
const { dynamicTags } = toRefs(tagState);

watch(
    () => props.labels,
    () => {
        tagState.dynamicTags = labels?.value ? [...labels.value] : [];
    }
);

const showAdd = computed(() => {
    if (props.limit) {
        return !inputVisible.value && dynamicTags.value.length < props.limit;
    } else {
        return !inputVisible.value;
    }
});

const handleClose = (tag) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
    emit('update:labels', dynamicTags.value);
};

const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
        InputRef.value?.input?.focus();
    });
};

const handleInputConfirm = () => {
    const value = inputValue.value.trim();
    if (value) {
        dynamicTags.value.push(value);
    }
    emit('update:labels', dynamicTags.value);
    inputVisible.value = false;
    inputValue.value = '';
};
</script>
<style lang="scss" scoped>
.el-tag {
    margin-right: 8px;
    background: #f6f6f9;
    border: 1px solid #dcdde6;
    border-radius: 2px;
    font-size: 12px;
    color: #454655;
    line-height: 12px;
}
.el-input {
    width: 88px;
    :deep(.el-input__wrapper) {
        height: 24px !important;
    }
    :deep(.el-input__inner) {
        background: #f6f6f9;
        border-radius: 2px;
        font-size: 12px;
        color: #454655;
        line-height: 12px;
    }
}
</style>
